<?php
/**
 * Profiler Class
 *
 * @package Profiler
 * @copyright (C) 2002-2007 The Digital Development Foundation
 * @license GPL {@link http://www.gnu.org/licenses/gpl.html}
 *
 * @subpackage Profiler
 */

class sfProfiler
{
    var $dbconn;

    public function __construct(){
        $this->dbconn =& xarDBGetConn();
    }

    public function onLoad()
    {
        $this->setQueryLog();
        $start_time = $this->startMicrotime();
        return $start_time;
    }

    public function postLoad($start_time)
    {
        $this->getVariables();
        $this->calculatePageSpeed($start_time);
        $this->getMemoryUsage();
        $this->getIncludedFiles();
    }

    public function setQueryLog()
    {
        $query = "SET GLOBAL general_log = 'ON'";
        if (!$this->dbconn->Execute($query)) return;
        $query = "SET GLOBAL slow_query_log = 'ON';";
        if (!$this->dbconn->Execute($query)) return;
        $query = "SET GLOBAL log_output = 'TABLE';";
        if (!$this->dbconn->Execute($query)) return;
        $query = "TRUNCATE mysql.general_log";
        if (!$this->dbconn->Execute($query)) return;
        return true;
    }

    public function getGeneralLog()
    {
        $query = "SELECT event_time,
                                    argument
                        FROM mysql.general_log";
        $result = $this->dbconn->Execute($query);
        if (!$result) return;

        $log = array();
        while(!$result->EOF) {
            list($event_time, $argument) = $result->fields;
                $log[] = array('event_time' => $event_time,
                                      'query'         => $argument);
                $result->MoveNext();
        }

        $foo = print_r($log);
        return $foo;
    }

    public function getSlowLog()
    {
        $query = "SELECT query_time,
                                    sql_text
                        FROM mysql.slow_log";
        $result = $this->dbconn->Execute($query);
        if (!$result) return;

        $log = array();
        while(!$result->EOF) {
            list($query_time, $sql_text) = $result->fields;
                $log[] = array('query_time' => $query_time,
                                      'query'         => $sql_text);
                $result->MoveNext();
        }

        $foo = print_r($log);
        return $foo;
    }

    public function truncateSlowLog()
    {
        $query = "TRUNCATE mysql.slow_log";
        if (!$this->dbconn->Execute($query)) return;
        return true;
    }

    public function explainQuery($incoming_query)
    {
        $query = "EXPLAIN $incoming_query";
        $result = $this->dbconn->Execute($query);
        if (!$result) return;
/*
        $data = array();
        while(!$result->EOF) {
            list($table, $type, $possible_keys, $	key, $key_len, $	ref	rows, $Extra) = $result->fields;
                $data[] = array('table' => $table,
                                        'type' => $type,
                                        'possible_keys' => $possible_keys,
                                        'key_len' => $key_len,
                                        'refrows'   => $refrows,
                                        'extra' => $extra);
                $result->MoveNext();
        }
*/
        $foo = print_r($data);
        return $foo;
    }

    public function getVariables()
    {
        $foo = xarVarGetCached('Template.Variables.Profiler', 'template_vars');
        $bar = print_r($foo);
        return $bar;

    }

    public function startMicrotime()
    {
        $time_start = microtime(true);
        return $time_start;
    }

    public function calculatePageSpeed($time_start)
    {
        $time_end = microtime(true);
        $total_time = $time_end - $time_start;
        xarVarSetCached('Profiler.Measurements', 'page_execution_time', $total_time);
        $foo = print_r($total_time);
        return $foo;
    }

    public function getConfigVars()
    {


    }

    public function getMemoryUsage()
    {
        $data['memory_usage'] = $this->getFileSizeReadable(memory_get_usage());
        $data['peak_memory_usage'] = $this->getFileSizeReadable(memory_get_peak_usage());
        $data['memory_available'] = ini_get("memory_limit");
        xarVarSetCached('Profiler.Measurements', 'memory_usage', $data);
        $foo = print_r($data);
        return $foo;
    }

    public function getIncludedFiles()
    {
        $files = get_included_files();
        xarVarSetCached('Profiler.Measurements', 'included_files', $files);
        $foo = print_r($files);
        return $foo;
    }

    public function getLogOutput()
    {
        $log = xarCoreGetVarDirPath() . '/logs/log.txt';
        if (file_exists($log)) {
            $file = file_get_contents ($log);
            $foo = print_r($file);
            file_put_contents($log, '');
        } else {
            $foo = false;
        }
        return $foo;

    }




    /**
     * Return human readable sizes
     *
     * @author      Aidan Lister <aidan@php.net>
     * @version     1.3.0
     * @link        http://aidanlister.com/2004/04/human-readable-file-sizes/
     * @param       int     $size        size in bytes
     * @param       string  $max         maximum unit
     * @param       string  $system      'si' for SI, 'bi' for binary prefixes
     * @param       string  $retstring   return string format
     */
    private function getFileSizeReadable($size, $max = null, $system = 'si', $retstring = '%01.2f %s')
    {
        // Pick units
        $systems['si']['prefix'] = array('B', 'K', 'MB', 'GB', 'TB', 'PB');
        $systems['si']['size']   = 1000;
        $systems['bi']['prefix'] = array('B', 'KiB', 'MiB', 'GiB', 'TiB', 'PiB');
        $systems['bi']['size']   = 1024;
        $sys = isset($systems[$system]) ? $systems[$system] : $systems['si'];

        // Max unit to display
        $depth = count($sys['prefix']) - 1;
        if ($max && false !== $d = array_search($max, $sys['prefix'])) {
            $depth = $d;
        }

        // Loop
        $i = 0;
        while ($size >= $sys['size'] && $i < $depth) {
            $size /= $sys['size'];
            $i++;
        }

        return sprintf($retstring, $size, $sys['prefix'][$i]);
    }
}
